''' @copyright:Copyright (c) 2006-2007, PreFab Software Inc. '''

from django import template
from django.conf import settings

from blogmaker.util import expand_shortcuts

register = template.Library()

register.filter('expand_shortcuts', template.defaultfilters.stringfilter(expand_shortcuts))

@register.simple_tag
def setting(name):
    return getattr(settings, name)
    
    
@register.tag
def getsetting(parser, token):
    ''' Access a setting and assign a variable in the template
        Usage: {% getsetting setting as var %}
    '''
    args = token.split_contents()
    if len(args) != 4:
        raise template.TemplateSyntaxError, "%r tag requires two or four arguments" % args[0]
    
    return GetSettingNode(args[1], args[3])

class GetSettingNode(template.Node):
    def __init__(self, setting, var):
        self.setting = setting
        self.var = var
        
    def render(self, context):
        value = getattr(settings, self.setting)
        context[self.var] = value
        return ''
        
        
@register.tag('with')
def do_with(parser, token):
    """
    Add a value to the context (inside of this block) for easy access.

    Example::

        {% with person.addresses.all as addresses %}
            {% if addresses %}
                <h3>Addresses</h3>
                {% for address in addresses %}
                   ...
                {% endfor %}
            {% endif %}
        {% endwith %}
    
    From http://www.djangosnippets.org/snippets/132/
    """
    bits = list(token.split_contents())
    if len(bits) != 4 or bits[2] != "as":
        raise template.TemplateSyntaxError, "%r expected format is 'value as name'" % token.contents[0]
    var = parser.compile_filter(bits[1])
    name = bits[3]
    nodelist = parser.parse(('endwith',))
    parser.delete_first_token()
    return WithNode(var, name, nodelist)

class WithNode(template.Node):
    def __init__(self, var, name, nodelist):
        self.var = var
        self.name = name
        self.nodelist = nodelist

    def __repr__(self):
        return "<WithNode>"

    def render(self, context):
        val = self.var.resolve(context)
        context.push()
        context[self.name] = val
        output = self.nodelist.render(context)
        context.pop()
        return output
